//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.ww.springboot.springstudy.config;

import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;
import com.netflix.loadbalancer.ZoneAvoidanceRule;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

public class TmsRibbonRule extends ZoneAvoidanceRule {
    private List<InetAddress> localHosts;

    public TmsRibbonRule() {
    }

    public Server choose(Object key) {
        ILoadBalancer lb = this.getLoadBalancer();
        List<Server> eligible = this.getPredicate().getEligibleServers(lb.getAllServers(), key);
        if (Objects.isNull(this.localHosts)) {
            this.localHosts = this.getInetAddresses();
        }

        Optional<Server> first = eligible.stream().filter((stance) -> {
            return this.localHosts.stream().filter((inetAddress) -> {
                return stance.getHost().equalsIgnoreCase(inetAddress.getHostAddress());
            }).findFirst().isPresent();
        }).findFirst();
        if (first.isPresent()) {
            return (Server) first.get();
        } else {
            Optional<Server> any = eligible.stream().filter((instance) -> {
                return !instance.getHost().startsWith("192");
            }).findAny();
            return any.isPresent() ? (Server) any.get() : super.choose(key);
        }
    }

    private List<InetAddress> getInetAddresses() {
        ArrayList localHosts = new ArrayList();

        try {
            Enumeration en = NetworkInterface.getNetworkInterfaces();

            while (en.hasMoreElements()) {
                NetworkInterface ni = (NetworkInterface) en.nextElement();
                Enumeration enumInetAddr = ni.getInetAddresses();

                while (enumInetAddr.hasMoreElements()) {
                    InetAddress inetAddress = (InetAddress) enumInetAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress() && inetAddress.isSiteLocalAddress()) {
                        localHosts.add(inetAddress);
                    }
                }
            }
        } catch (SocketException var6) {
        }

        return localHosts;
    }
}
